package io.persimmon.core.util;

import io.persimmon.core.exception.PersimmonExceptionFactory;

import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class ObjectUtil {

    private static Map<Class<?>, Object> SINGLE_INSTANCE = new ConcurrentHashMap<>();

    public static String toString(Object data) {
        if (Objects.isNull(data)) {
            return "null";
        }
        if (data instanceof Number) {
            return data.toString();
        } else if (data instanceof String) {
            return data.toString();
        } else if (data instanceof Date) {
            Date d = (Date) data;
            return d.getTime() + "";
        } else {
            return JSONUtil.toJson(data);
        }
    }

    public static void assertIfNull(Object data) {
        PersimmonExceptionFactory.assertIf(Objects.isNull(data), "data is not null");
    }


    public static <T> T getSingleInstance(Class<T> clazz) {
        if (Objects.isNull(clazz)) {
            return null;
        }
        if (SINGLE_INSTANCE.containsKey(clazz)) {
            return (T) SINGLE_INSTANCE.get(clazz);
        } else {
            try {
                T instance = clazz.newInstance();
                SINGLE_INSTANCE.put(clazz, instance);
                return instance;
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
